package me.winds.wrapper.base.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.gyf.immersionbar.ImmersionBar;

import me.winds.widget.usage.TitleView;
import me.winds.widget.usage.ToastView;
import me.winds.wrapper.R;
import me.winds.wrapper.base.adapter.ViewHelper;
import me.winds.wrapper.base.listener.OnViewHelper;
import me.winds.wrapper.core.manager.task.TaskManager;
import me.yokeyword.fragmentation.SupportActivity;

/**
 * Author:  winds
 * Data:    2017/4/11
 * Desc:
 */

public abstract class WrapperCompatActivity extends SupportActivity {
    private boolean isAutoFocus = true;  //自动显示和隐藏输入法
    private boolean isAutoClearFocus = true;  //是否自动清除焦点
    private long lastTime;
    private boolean interceptEnable;  //是否拦截快速点击事件

    protected LinearLayout rootView;      //根View
    protected FrameLayout containerView;  //承装view
    protected View contentView;           //内容View
    protected TitleView titleView;        //标题View
    protected Activity mActivity;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        beforeOnCreate();
        setContentView(R.layout.activity_wrapper);
        initView();
        initTitleView();
        initContentView();
        initImmersionBar();
        initView(savedInstanceState, titleView, getIntent());
    }

    @Override
    protected void onDestroy() {
        if (isImmersionBarEnable()) {

        }
        super.onDestroy();
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //快速点击拦截
        if (!interceptEnable && (ev != null && ev.getAction() == MotionEvent.ACTION_DOWN)) {
            if (isInvalidClick()) {
                return true;
            }
        }
        //键盘拦截判断
        if (isAutoFocus) {
            if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                View v = getCurrentFocus();
                if (isShouldHideInput(v, ev)) {
                    if (isAutoClearFocus) {
                        v.clearFocus(); //临时增加
                    }
                    hideKeyboard(v);
                }
                return super.dispatchTouchEvent(ev);
            }
            // 其他组件响应点击事件
            if (getWindow().superDispatchTouchEvent(ev)) {
                return true;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 返回值为0或者-1时不添加
     *
     * @return
     */
    protected abstract int getViewLayout();

    protected abstract void initView(Bundle savedInstanceState, TitleView titleView, Intent intent);

    protected void beforeOnCreate() {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);   //去除默认actionbar
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//统一管理竖屏
    }

    private void initView() {
        mActivity = this;
        rootView = findViewById(R.id.root);
        titleView = findViewById(R.id.title);
        containerView = findViewById(R.id.container);
    }

    private void initTitleView() {
        if (!isUseTitle()) {
            findViewById(R.id.layout_title).setVisibility(View.GONE);
        } else {
            titleView.setChildClickListener(R.id.iv_title_left, onBackClick());
        }
    }

    protected void initContentView() {
        if (getViewLayout() > 0) {
            contentView = View.inflate(this, getViewLayout(), null);
            addContentView(contentView);
        }
    }

    protected void addContentView(View view) {
        containerView.addView(view);
    }

    protected boolean isImmersionBarEnable() {
        return true;
    }

    protected void initImmersionBar() {
        if (isImmersionBarEnable()) {
            setImmersionBar();
        }
    }

    protected void setImmersionBar() {

    }

    /**
     * 标题返回按钮 如需重写 覆盖此方法即可
     *
     * @return
     */
    protected View.OnClickListener onBackClick() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressedSupport();
            }
        };
    }

    protected boolean isUseTitle() {
        return true;
    }

    protected View getContentView() {
        return contentView;
    }

    protected LinearLayout getRootView() {
        return rootView;
    }

    protected View getContainerView() {
        return containerView;
    }

    protected TitleView getTitleView() {
        return titleView;
    }

    /**
     * 设置是否拦截快速点击
     *
     * @param interceptEnable 默认拦截   设置不拦截请设置为 false
     */
    protected void setInterceptEnable(boolean interceptEnable) {
        this.interceptEnable = !interceptEnable;
    }

    /**
     * 判断是否是快速点击
     *
     * @return
     */
    public boolean isInvalidClick() {
        long time = System.currentTimeMillis();
        long duration = time - lastTime;
        if (duration < 400) {
            return true;
        } else {
            lastTime = time;
            return false;
        }
    }

    public void setAutoClearFocus(boolean isAutoClearFocus) {
        this.isAutoClearFocus = isAutoClearFocus;
    }

    public void hideKeyboard(View v) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    /**
     * 判断键盘是否应该隐藏
     * 点击除EditText的区域隐藏
     *
     * @param v
     * @param event
     * @return
     */
    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                ((EditText) v).setCursorVisible(true);
                return false;
            } else {
                ((EditText) v).setCursorVisible(false);  //隐藏光标
                return true;
            }
        }
        return false;
    }

    /**
     * 设置键盘显否
     *
     * @param v
     * @param visible
     */
    protected void setKeyboardVisible(View v, boolean visible) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            if (visible) {
                imm.showSoftInput(v, 0);
            } else {
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
    }

    /**
     * 实例化对应layoutId的view同时生成ViewHelper帮助类
     *
     * @param group    可为null
     * @param layoutId
     * @param listener
     * @return
     */
    protected View getHelperView(ViewGroup group, int layoutId, OnViewHelper listener) {
        ViewHelper helper = new ViewHelper(getLayoutInflater().inflate(layoutId, group == null ? null :
                group instanceof RecyclerView ? (ViewGroup) group.getParent() : group, false));
        if (listener != null) {
            listener.help(helper);
        }
        return helper.getItemView();
    }

    /**
     * 设置自动隐藏输入法
     *
     * @param isAutoFocus 默认 true 自动隐藏
     */
    protected void setAutoFocus(boolean isAutoFocus) {
        this.isAutoFocus = isAutoFocus;
    }


    protected void showRemoteToast(final String msg, final int duration) {
        TaskManager.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                ToastView.showToastInCenter(mActivity, msg, duration);
            }
        });
    }

    protected void showRemoteToast(final String msg) {
        TaskManager.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                showToast(msg);
            }
        });
    }

    /**
     * 普通Toast提示
     *
     * @param msg
     */
    protected void showToast(String msg) {
        ToastView.showToastInCenter(mActivity, msg, Toast.LENGTH_LONG);
    }

    /**
     * 图文样式的Toast提示
     *
     * @param msg
     * @param resId
     */
    protected void showToast(String msg, int resId) {
        ToastView.showVerticalToast(mActivity, msg, resId);
    }
}
